from fastapi import APIRouter, Depends
from ..schemas import RoleInSchema, RoleOutSchema,DeptOutTreeSchema
from ..models import Roles,UserInfo,Menu
from src.utils.common_response import APIResponse
from typing import List

router = APIRouter()


@router.post("/role", description="新增角色")
async def add_role(role: RoleInSchema):
    menus = role.menus
    del role.menus
    single_role = await Roles.create(**role.dict())
    if menus:
        await single_role.menus.clear()
        for menu_id in menus:
            menu = await Menu.get(id=menu_id)
            await single_role.menus.add(menu)
    return APIResponse(msg='新增成功')


@router.delete("/roles", description='删除接口，单挑多条都支持')
async def delete_role(ids: List[int]):
    res = await Roles.filter(id__in=ids).update(is_delete=True)
    return APIResponse(msg="删除成功")


@router.get("/roles", description="查询所有角色")
async def get_all_role():
    roles = await Roles.filter(is_delete=False).all()
    role_dicts = [await RoleOutSchema.from_orm_recursive(role) for role in roles]
    return APIResponse(results=role_dicts)


@router.get("/roles/{role_id}", description='查询角色详情')
async def get_role(role_id: int):
    role = await Roles.filter(id=role_id).prefetch_related('menus').prefetch_related('depts').first()
    role_dict = await RoleOutSchema.from_orm_recursive(role)
    return APIResponse(result=role_dict)


@router.put("/roles/{role_id}", description="修改角色")
async def put_role(role_id: int, role: RoleInSchema):
    menus = role.menus
    del role.menus
    await Roles.filter(id=role_id).update(**role.dict())
    if menus:
        single_role = await Roles.filter(id=role_id).first()
        await single_role.menus.clear()
        for menu_id in menus:
            menu = await Menu.get(id=menu_id)
            await single_role.menus.add(menu)
    return APIResponse(msg="角色修改成功")

